#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>

#define MAX_LINE 1024

int main(int argc, char **argv)
{
    if (argc != 3)
    {
        fprintf(stderr, "Usage: %s -n <file>\n", argv[0]);
        exit(1);
    }
    int n = atoi(argv[1] + 1); // 解析-n参数
    int fd = open(argv[2], O_RDONLY);
    char buf[MAX_LINE];
    off_t pos = lseek(fd, 0, SEEK_END);
    int line_count = 0;
    while (pos > 0 && line_count <= n)
    {
        pos--;
        lseek(fd, pos, SEEK_SET);
        read(fd, buf, 1);
        if (buf[0] == '\n')
            line_count++;
    }
    lseek(fd, pos + 1, SEEK_SET);
    while (read(fd, buf, 1) > 0)
        write(1, buf, 1);
    close(fd);
    return 0;
}